package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    DtsAdminMapper adminMapper;
    @Override
    public DtsAdmin findByUsernma(String username) {
        LambdaQueryWrapper<DtsAdmin> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DtsAdmin::getUsername,username);
        DtsAdmin dtsAdmin = adminMapper.selectOne(queryWrapper);

        return dtsAdmin;
    }

    @Override
    public IPage<DtsAdmin> selectByPage(Integer page, Integer limit, String username, String sort, String order) {
        IPage<DtsAdmin> iPage=new Page<>(page,limit);
        QueryWrapper<DtsAdmin> queryWrapper=new QueryWrapper();
        if(!StringUtils.isEmpty(username)){
            queryWrapper.like("username",username);
        }
        if(!StringUtils.isEmpty(sort)&&!StringUtils.isEmpty(order)){
            if(order.equalsIgnoreCase("desc")){
                queryWrapper.orderByDesc(sort);
            }else {
                queryWrapper.orderByAsc(sort);
            }
        }
        queryWrapper.eq("deleted",false);


        IPage iPage1 = adminMapper.selectPage(iPage, queryWrapper);
        return iPage1;
    }

    @Override
    public DtsAdmin update(DtsAdmin dtsAdmin) {
        DtsAdmin admin = adminMapper.selectById(dtsAdmin.getId());
        if(admin.getPassword()==null || !admin.getPassword().equals(dtsAdmin.getPassword())){
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            String encode = passwordEncoder.encode(dtsAdmin.getPassword());
            dtsAdmin.setPassword(encode);
        }
        dtsAdmin.setUpdateTime(new Date());
        adminMapper.updateById(dtsAdmin);
        return dtsAdmin;
    }

    @Override
    public DtsAdmin insert(DtsAdmin dtsAdmin) {
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(dtsAdmin.getPassword());
        dtsAdmin.setPassword(encode);
        adminMapper.insert(dtsAdmin);
        dtsAdmin.setAddTime(new Date());
        dtsAdmin.setUpdateTime(new Date());
        dtsAdmin.setDeleted(false);


        return dtsAdmin;
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.selectById(id);
    }


}
